package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

import database.dao.UserHibernate;

import model.User;
import model.UserAuth;
import model.subjects.Subject;

/**
 * 
 * @author Matu
 * 
 */
@WebServlet(value = "/LoginServlet", loadOnStartup = 1)
public class LoginServlet extends HttpServlet {
	
	
	static Logger logger = Logger.getLogger (LoginServlet.class);
	public void init() {
			
		BasicConfigurator.configure();
		logger.error("LoginServlet.init(): mind loodi");
		}

	
	String username = null;
	String password = null;
	User MyUser = null;

	User user = new User();
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, java.io.IOException {

		HttpSession session = request.getSession(true);
		response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");

		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		
		
		System.out.println("ok");

		if (request.getParameter("action") != null) {
			if (request.getParameter("action").equals("logout")) {

				System.out.println("trying to logout");
				HttpSession destroyable_session = request.getSession(false);
				if (destroyable_session != null) {
					destroyable_session.invalidate();
//					session.setAttribute("user", null);
					RequestDispatcher rd = getServletContext()
							.getRequestDispatcher("/Login.jsp");
					rd.forward(request, response);

				}
			}

			if (request.getParameter("action").equals("login")) {

				if (request.getParameter("username") != null) {
					username = request.getParameter("username");
				}

				if (request.getParameter("password") != null) {
					password = request.getParameter("password");

					System.out.println(request.getParameter("password"));
				}

				if ((!(username.equals(""))) && (!(password.equals("")))) {

					UserAuth MyAuth = new UserAuth();
					MyUser = MyAuth.auth(username, password);
		
					
//					UserHibernate userHibernate = new UserHibernate();
//					MyUser = userHibernate.getUserFromDB(username,password);
					// HIBERNATE USER= BIGDECIMAL!!

					// if user valid =>login.
					// if MyUser==true for hibernate
		
					
					if (MyUser != null) {

						// see on siin ID!(user), p�rast refaktoreerida vb!
						session.setAttribute("user", user.getUser());
						session.setAttribute("username", user.getUsername());
						session.setAttribute("first_name",
								MyUser.getFirst_name());
						session.setAttribute("last_name", MyUser.getLast_name());

						request.setAttribute("results", new LinkedList<Subject>());
						getServletConfig().getServletContext()
								.getRequestDispatcher("/MainPage.jsp")
								.forward(request, response);

					}

					else {
						out.println("Login failed, unknown user, try again.");
						RequestDispatcher rd = getServletContext()
								.getRequestDispatcher("/Login.jsp");
						rd.forward(request, response);
						

					}
				}
				// Kui login v�ljad t�hjad siis saada kasutaja tagasi login page
				else {
				
					RequestDispatcher rd = getServletContext()
							.getRequestDispatcher("/Login.jsp");
					rd.forward(request, response);

				} // end else

			} // end if, request.getParameter("action").equals("login")

		} // end if request.getParameter("action")!=null

		else {


			RequestDispatcher rd = getServletContext().getRequestDispatcher(
					"/Login.jsp");
			rd.forward(request, response);

		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, java.io.IOException {
		doGet(request, response);
	}

}
